/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejemploadicionararboles;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

public class LazyTreeItem extends TreeItem<String> {
  /** The depth of this tree item in the {@link TreeView}. */
  private final int depth;
  /** Control if the children of this tree item has been loaded. */
  private boolean hasLoadedChildren = false;
  
  public LazyTreeItem(String itemText, int depth) {
   super(itemText);
   this.depth = depth;
  }
  
  @Override
  public ObservableList<TreeItem<String>> getChildren() {
   if (hasLoadedChildren == false) {
    loadChildren();
   }
   return super.getChildren();
  }
  
  @Override
  public boolean isLeaf() {
   if (hasLoadedChildren == false) {
    loadChildren();
   }
   return super.getChildren().isEmpty();
  }
  
  /** Create some dummy children for this item. */
  @SuppressWarnings("unchecked") // Safe to ignore since we know that the types are correct.
  private void loadChildren() {
   hasLoadedChildren = true;
   int localDeepth = depth + 1;
   LazyTreeItem child1 = new LazyTreeItem("Child 1 (deepth = " + localDeepth + ")",
        localDeepth);
   LazyTreeItem child2 = new LazyTreeItem("Child 2 (deepth = " + localDeepth + ")",
        localDeepth);
       super.getChildren().setAll(child1, child2);
  }
  
  /** Return the depth of this item within the {@link TreeView}.*/
  public int getDepth() {
   return depth;
  }
 }
